package cc.magicjson.synthesis.service;



import cc.magicjson.synthesis.chain.DiscountChecker;
import cc.magicjson.synthesis.factory.DiscountCheckerFactory;
import cc.magicjson.synthesis.context.DiscountContext;
import cc.magicjson.synthesis.model.Order;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 折扣服务，负责协调折扣计算流程
 */
public class DiscountService {
    // 积分兑换比例：多少积分兑换1元
    private final int pointsPerYuan;

    // 使用ReentrantLock保证并发安全
    private final Lock lock = new ReentrantLock();

    public DiscountService(int pointsPerYuan) {
        this.pointsPerYuan = pointsPerYuan;
    }

    /**
     * 计算订单折扣
     * @param order 要计算折扣的订单
     * @return 计算折扣后的订单
     */
    public Order calculateDiscount(Order order) {
        // 创建折扣计算上下文
        DiscountContext context = new DiscountContext(order);

        // 创建折扣检查责任链
        DiscountChecker discountChain = DiscountCheckerFactory.createDiscountChain(pointsPerYuan);

        // 加锁保证并发安全
        lock.lock();
        try {
            // 执行折扣计算
            discountChain.process(context);
            return context.getOrder();
        } catch (Exception e) {
            // 出现异常时进行回滚
            discountChain.rollback(context);
            throw e;
        } finally {
            lock.unlock();
        }
    }

}
